/**
 * 路由配置标准
 * 路由不能一级配置，如果只有一个页面没有子页面，需要创建一个父级路由 component为layout然后子路由为当前页面
 * 当子级路由只有一个时 会在侧边导航栏渲染成一个单独的导航
 * meta的title会渲染城导航栏的title，icon都会渲染城导航栏的图标
 * 添加sidebar: false的路由将不会在侧边栏渲染
 */

import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '../layout/IndexView.vue'
import beforeEach from './beforeEach'

Vue.use(VueRouter)

const createRouter = () => new VueRouter({
  mode: 'hash',
  base: import.meta.env.BASE_URL,
  routes: [
    {
      path: '/',
      redirect: '/home',
      meta: {
        sidebar: false
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
      meta: {
        title: '登录',
        sidebar: false,
      }
    },
    {
      path: '/home',
      name: 'home',
      component: layout,
      redirect: '/home/index',
      meta: {
        title: '首页',
        icon: 'el-icon-s-home'
      },
      children: [
        {
          path: '/home/index',
          name: 'homeIndex',
          component: () => import('@/views/HomeView.vue'),
          meta: {
            title: '首页'
          }
        },
      ]
    },
    {
      path: '/404',
      component: () => import('@/views/404.vue'),
      meta: {
        sidebar: false
      }
    },
  ]
})

const router = createRouter()
beforeEach(router)

// 解决路由跳转到当前路由的重复报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
